/**
 * 打印
 */
const fs = require('fs');
const ipp = require('ipp');
const printList = require('../config/PrintList');

let JobId = 0;

const printer = ipp.Printer(printList['917']);
printer.execute('Create-Job', {
  'operation-attributes-tag': {
    'requesting-user-name': 'zfc-gx',
  },
  'job-attributes-tag': {
    'media': 'iso_a4_210x297mm',
  }
}, function(err, res){
  JobId = res['job-attributes-tag']['job-id'];
  console.log('创建job====>', res);
  printer.execute('Get-Jobs', {
    'operation-attributes-tag': {
       'requested-attributes': [
         'job-id',
       ]
     }
  }, function(err, res){
    console.log('获取其他job并取消--->', res);
    Array.isArray(res['job-attributes-tag']) && res['job-attributes-tag'].forEach(job => {
      if(job['job-id'] != JobId) {
        printer.execute('Cancel-Job', {
          'job-id': job['job-id'],
          'requesting-user-name': 'zfc-gx',
        }, function(err, res) {
          console.log('res====', res);
        });
      }
    });
  });
});


/**
 * 立即打印
 */

let print = async (ctx, next) => {
  const data = ctx.request.body;
  const file = ctx.request.files?.file;
  if(!file) {
    ctx.body = {
      code: 0,
      msg: '请选择打印文件',
      data: {}
    };
    return;
  }
  
  const fileData = await fs.readFileSync(file.filepath);
  let send_msg = {
    'operation-attributes-tag': {
      'job-id': JobId,
      'requesting-user-name': 'zfc-gx',
      'document-format': 'application/pdf'
    },
    // 'job-attributes-tag': {
    //   'copies': data.num,
    //   'print-color-mode': data.color == '1' ? 'color' : 'monochrome',
    //   // 'sides': data.doublSided == '1' ? 'two-sided-long-edge' : 'one-sided', //  'sides-supported': [ 'one-sided', 'two-sided-short-edge', 'two-sided-long-edge' ],
    // },
    data: fileData
  };
  console.log('file.mimetype=====>', file.mimetype);
  if(file.mimetype.split('/')[0] == 'image') {
    send_msg['operation-attributes-tag']['document-format'] = file.mimetype;
  }
  if(file.mimetype.indexOf('vnd') > 0) {
    send_msg['operation-attributes-tag']['document-format'] = 'application/vnd.hp-PCLXL';
  }
  const printRes = await new Promise((resolve) => {
    // const printer = ipp.Printer(printList[data.print]);
    console.log('JobId====>', JobId);
    // Create-Job Print-Job
    printer.execute('Send-Document', send_msg, function(err, res){
      console.log(err, res);
      // console.log(err);
      if(!err) resolve(res);
    });
  });
  if(printRes.statusCode == 'successful-ok') {
    ctx.body = {
      code: 0,
      msg: '打印成功',
      data: {
        file: file.originalFilename
      }
    };
  } else if (printRes.statusCode == 'server-error-busy') {
    ctx.body = {
      code: -1,
      msg: '打印机正忙，请稍后再试',
      data: {
        file: file.originalFilename
      }
    };
  } else {
    ctx.body = {
      code: -2,
      msg: '打印可能遇到错误,请稍后再试',
      data: {
        file: file.originalFilename
      }
    };
  }
};


module.exports = {
  print
};